package com.itheima.response.g_download;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取下载文件名称
        String filename = request.getParameter("filename");

        //2. 获取文件在服务器的输入流对象
        InputStream is = getServletContext().getResourceAsStream("/img/" + filename);

        //2.1 设置响应头: 控制浏览器不要解析了, 以附件下载的方式处理服务器返回的数据
        response.setHeader("content-Disposition","attachment;filename="+filename);

        //3. 获取字节输出流
        ServletOutputStream sos = response.getOutputStream();

        //4. IO流拷贝
        IOUtils.copy(is,sos);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
